package ele_handler

import (
	"fmt"
	"go-yuque/logger"
	"go-yuque/yuque/util"
	"golang.org/x/net/html"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
)

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &cardLocaldocStruct{}
			h.elements = []string{"card"}
			h.attributes = map[string]string{"name": "localdoc"}
			return h
		})
}

type docBase struct {
	Src  string `json:"src" name:"附件URL"`
	Name string `json:"name" name:"附件名称,包含扩展名"`
}

type cardLocaldocStruct struct {
	BaseHandler
	docBase
	Size     int    `json:"size"`
	Ext      string `json:"ext"`
	Source   string `json:"source"`
	Status   string `json:"status"`
	Download bool   `json:"download"`
	TaskID   string `json:"taskId"`
	TaskType string `json:"taskType"`
	Type     string `json:"type"`
	Spacing  string `json:"__spacing"`
	Mode     string `json:"mode"`
	ID       string `json:"id"`
	Margin   struct {
		Top    bool `json:"top"`
		Bottom bool `json:"bottom"`
	} `json:"margin"`
}

func (l *cardLocaldocStruct) doHandle() (err error) {
	if len(l.downloadTocPath) <= 0 {
		logger.Errorf("[cardLocaldoc]下载路径为空")
		return fmt.Errorf("下载路径为空")
	}

	err = parseCardJson(l.node, l)
	if err != nil {
		logger.Errorf("[cardLocaldoc]解析异常")
		sb := strings.Builder{}
		err = html.Render(&sb, l.node)
		if err != nil {
			l.WriteTextContext(sb.String())
		}
		return err
	}

	err = getDoc(l.docBase, l.downloadTocPath, l)

	return
}

func getDoc(doc docBase, downloadTocPath string, base YuqueElementHandler) (err error) {

	if len(doc.Src) <= 0 || len(doc.Name) <= 0 {
		logger.Errorf("[getDoc]参数为空")
		return fmt.Errorf("参数为空")
	}

	ctx := base.GetCtx()
	if ctx == nil {
		logger.Errorf("[getDoc]ctx为空")
		return fmt.Errorf("ctx为空")
	}

	yqCookie, cookieOk := (*ctx).Value("yqCookie").(string)
	if !cookieOk {
		logger.Errorf("[getDoc]cookie为空")
		return fmt.Errorf("cookie为空")
	}

	baseDir, assetsPath := util.GetAssetsPath(downloadTocPath)

	docPath := filepath.Join(assetsPath, doc.Name)

	needDownloadDoc := true
	docState, _ := os.Stat(docPath)
	if docState != nil && !docState.IsDir() {
		logger.Infof("[getDoc]图片已存在:[%s]", docPath)
		needDownloadDoc = false
	}

	if needDownloadDoc {
		fb := util.FakeBrowserStruct{
			Url: doc.Src,
			Headers: http.Header{
				"Cookie": []string{yqCookie},
			},
		}

		fileBytes, err := fb.DoGet()
		if err != nil {
			logger.Errorf("[getDoc]下载附件报错,error:%v", err)
			return err
		}

		err = os.WriteFile(
			docPath,
			fileBytes, 0666)
		if err != nil {
			return err
		}
		logger.Infof("[getDoc]附件下载到:[%s]", docPath)
	}

	escapePath := url.PathEscape(fmt.Sprintf("%s.assets", baseDir))

	base.WriteTextContext(fmt.Sprintf("附件:[%s](%s)\n\n",
		doc.Name, filepath.Join(escapePath, doc.Name)))

	return nil
}
